package main

import (
	"gin-gorm-oj/router"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		// 在这里进行源站验证, 例如检查 Origin 头
		return true
	},
}

func main() {
	r := router.Router()
	r.GET("/ws/:sid", func(c *gin.Context) {
		sessionID := c.Param("sid")
		log.Printf("Received WebSocket connection for session ID: %s", sessionID)

		conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			log.Println("Failed to upgrade connection:", err)
			return
		}
		defer conn.Close()

		for {
			_, message, err := conn.ReadMessage()
			if err != nil {
				log.Println("WebSocket connection closed for session %s: %v", sessionID, err)
				break
			}
			log.Printf("Received message for session %s: %s", sessionID, message)

			err = conn.WriteMessage(websocket.TextMessage, []byte("Hello from server!"))
			if err != nil {
				log.Println("Error writing message:", err)
				break
			}
		}
	})

	r.Run(":7070")
}
